# pythonProject5/core/logger.py

import logging
import sys
from pathlib import Path
from core.config import settings
from datetime import datetime

# 获取项目根目录
ROOT_DIR = Path(__file__).parent.parent

# 日志输出目录（指向根目录的 logs/）
LOGS_DIR = ROOT_DIR / "logs"
LOGS_DIR.mkdir(exist_ok=True)  # 如果不存在就创建

# 创建 logger
logger = logging.getLogger("app")
logger.setLevel(settings.LOG_LEVEL)

# 避免重复添加 handler
if not logger.handlers:
    # 1. 输出到控制台
    console_handler = logging.StreamHandler(sys.stdout)
    console_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # 2. 输出到文件 logs/app.log，使用日期作为日志文件名
    log_filename = f"app_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
    file_handler = logging.FileHandler(LOGS_DIR / log_filename, encoding="utf-8")
    file_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s: %(message)s'
    )
    file_handler.setFormatter(file_formatter)
    logger.addHandler(file_handler)

    logger.info(f"日志记录器已启动，日志文件: {log_filename}")

